package com.funtl.framework.security;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 超时检测
 * @author lusifer
 *
 */
public class TimeoutCheck {
	/**
	 * 检测方法执行是否超时
	 * @param callback 在回调中调用需要的方法
	 * @param seconds 超时时间，已秒为单位
	 * @return 0 - 执行成功, 1 - 方法中断, 2 - 发生异常, 3 - 方法超时
	 */
	public static int callable(Callable<String> callback, int seconds) {
		Executor executor = Executors.newSingleThreadExecutor();
		FutureTask<String> future = new FutureTask<String>(callback);
		executor.execute(future);
		
		try {
			String result = future.get(seconds, TimeUnit.SECONDS);
			System.out.println(result);
		} catch (InterruptedException e) {
			// TODO: handle exception
			// System.out.println("方法执行中断");
			future.cancel(true);
			return 1;
		} catch (ExecutionException e) {
			// System.out.println("Excution异常");
			// TODO: handle exception
			future.cancel(true);
			return 2;
		} catch (TimeoutException e) {
			// TODO: handle exception
			// System.out.println("方法执行时间超时");
			future.cancel(true); //取消方法执行，如果不取消，即使超时，方法也会继续执行下去
			return 3;
		}
		
		return 0;
	}
	
	public static void main(String[] args) {
		int result = TimeoutCheck.callable(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(2000);
				System.out.println("Hello World");
				return "执行成功可以返回消息";
			}
		}, 1);
		
		System.out.println(result);
	}
}
